import { nextTick, onActivated, onDeactivated, onMounted, onUnmounted, ref } from "vue";

type TOptions = {
  mounted?: boolean; // 挂在时执行
  duration?: number; // 延迟时间
  initialValue?: any;
  defaultValue?: any;
  reverseValue?: any;

  autoRestore?: boolean
};

export default function useDelay<T = boolean>(options?: TOptions) {
  const {
    duration,
    mounted = true,
    autoRestore = false,

    initialValue,
    defaultValue = false,
    reverseValue = true,
  } = options || {};


  const state = ref<T>(initialValue ?? defaultValue);

  function restore() {
    state.value = defaultValue
  }

  function reset() {
    restore()
    run();
  }

  function setRight() {
    state.value = reverseValue;
  }

  function run() {
    duration ? setTimeout(setRight, duration) : nextTick(setRight);
  }

  function handleOnActive() {
    mounted && run()
  }

  function handleOnDeactive() {
    autoRestore && restore()
  }

  onMounted(handleOnActive);
  onActivated(handleOnActive)

  onDeactivated(handleOnDeactive)
  onUnmounted(handleOnDeactive)

  return [state, { reset }] as [typeof state, {reset: typeof reset}];
}
